package at.ac.tuwien.mg.wh.client;

import java.util.List;

import javax.naming.InitialContext;

import org.activiti.engine.delegate.DelegateExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.mg.bean.Order;
import at.ac.tuwien.mg.wh.WarehouseBeanRemote;
import at.ac.tuwien.mg.wh.dto.ItemDTO;

public class CheckoutClient extends Client {

	private static Logger log = LoggerFactory.getLogger(CheckoutClient.class);

	@SuppressWarnings({ "unchecked" })
	@Override
	public void execute(DelegateExecution execution) throws Exception {

		InitialContext ctx = new InitialContext();
		WarehouseBeanRemote bean = lookupStateless(ctx);
		
		//////
		
		List<ItemDTO> toBook = (List<ItemDTO>) execution.getVariable("toBook");
		List<ItemDTO> toOrder = (List<ItemDTO>) execution.getVariable("toOrder");
		Order order = (Order) execution.getVariable("currentOrder");
		
		List<ItemDTO> originalRequest = orderToItemList(order);
		Long userId = toLong(execution.getProcessInstanceId().toString());
	
		
		for(ItemDTO oneFinal: originalRequest){
			oneFinal.setNumber(0);
			
			if(order.getDeliveryOK()){
				for(ItemDTO oneOrdered: toOrder){
					if(oneOrdered.getCatalogId().equals(oneFinal.getCatalogId())){
						oneFinal.setNumber(oneFinal.getNumber()+oneOrdered.getNumber());
					}
				}	
			}
			for(ItemDTO oneBooked: toBook){
				if(oneBooked.getCatalogId().equals(oneFinal.getCatalogId())){
					oneFinal.setNumber(oneFinal.getNumber()+oneBooked.getNumber());
				}
			}	
		}
		
		bean.removeItems(originalRequest, userId);
		
		log("[CHECKOUT]\nCheckout from stock: "+originalRequest+" for user: "+userId);
		
		//////
		
		closeContext(ctx);
	}
}
